package main


import (
	"fmt"
	"net"
	"net/rpc"
	"time"
	connp "github.com/toolkits/conn_pool"
	rpcpool "github.com/toolkits/conn_pool/rpc_conn_pool"
)

type ArithRequest struct{

	A int
	B int
}

type ArithResponse struct{
	Result int
}

func createRpcConnPool() *connp.ConnPool{
	p := connp.NewConnPool("publish", "127.0.0.1:8007", int32(10), int32(5))
	p.New = func(connName string) (connp.NConn, error) {
		_, err := net.ResolveTCPAddr("tcp", p.Address)
		if err != nil {
			return nil, err
		}

		conn, err := net.DialTimeout("tcp", "127.0.0.1:8007", 2*time.Second)
		if err != nil {
			return nil, err
		}
		return rpcpool.NewRpcClient(rpc.NewClient(conn), connName), nil
	}
	return p
}

var pool = createRpcConnPool()

func request(){
	conn, err := pool.Fetch()	//从连接池中找出一个空闲的连接
	if err != nil {
		fmt.Println(11111111111, err)
		return
	}
	rpcConn := conn.(*rpcpool.RpcClient)
	if rpcConn.Closed() {
		pool.ForceClose(conn)
		fmt.Println("2222222", "conn closed")
		return
	}
	req := ArithRequest{9, 2}
	var res ArithResponse
	fmt.Println("abc")
	err = rpcConn.Call("Arith.Add", req, &res) // 加法运算
	if (err != nil){
		fmt.Println("33333333", err)
		pool.ForceClose(conn)

		fmt.Println("connetcion force closed ", conn.Name())
	}else{
		fmt.Println("444444444")

		pool.Release(conn)

		fmt.Println("connection released ", conn.Name())
	}
}

func main(){

	for {
		fmt.Println("start request")
		request()
		time.Sleep(1*time.Second)
	}
}
